import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/entity/pay/ai_pack_entity.dart';
import 'package:sports_new/server/api/ai_api.dart';
import 'package:sports_new/server/api/other_api.dart';
import 'package:sports_new/utils/utils.dart';

import '../../../entity/other/resource_entity.dart';
import '../../../entity/pay/recharge_entity.dart';
import '../../../server/api/coupon_api.dart';
import '../../../server/api/pay_api.dart';
import '../../../utils/routes.dart';
import '../../../utils/toast_utils.dart';
import '../../../utils/user.dart';
import '../../../view/pick/ai/ai_type.dart';
import '../../../widgets/pay_bottom_sheet.dart';

class AiPackLogic extends GetxController with GetTickerProviderStateMixin{
  List<ResourceEntity>? carousel;
  late AnimationController animationController;
  AiPackEntity? data;
  List<List<AiPackItem>> itemList = [];
  List<int>? days;
  List<double> priceSum = [];
  List<List<AiPackItem>> choices = [];
  List<SaleRule>? saleRule;
  List<int?> saleIndex = [];
  int _index = 0;
  ScrollController scrollController = ScrollController();

  double get animateValue => animationController.value;
  String get noticeText {
    if(choices[index].hasValue){
      if(saleRule.noValue) return "";
      if(saleIndex[index] != null){
        return "已选择${choices[index].length}款工具，享受${(getDiscount(index)*10).toInt()}折优惠";
      }else{
        return "至少选择${saleRule!.min}款工具才可以享受折扣哦";
      }
    }else{
      return "请选择模型工具";
    }
  }
  int get index => _index;

  set index(int value) {
    _index = value;
    update();
  }

  @override
  void onInit() {
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
    );
    animationController.addListener(() {
      update();
    });
    Utils.onEvent("wd_mxzh");
    super.onInit();
  }

  @override
  void onReady() async{
    await getData();
    // animate();
    scrollController.addListener(() {
      if(animateValue == 1) {
        animate();
      }
    });
    super.onReady();
  }

  void animate(){
    if(animationController.isCompleted){
      animationController.reverse();
    }else{
      animationController.forward();
    }
  }

  Future getData() async{

    carousel = Get.find<ResourceService>().lbt.where((element) => element.button == "ai_pack").toList();
    data = await AiApi.getAiPack();
    saleRule = data?.saleRule;
    days = [];
    data?.aiItem?.forEach((element) {
      if(element.days.hasValue && days!.contains(element.days) != true){
        days!.add(element.days!);
      }
    });
    days?.sort();
    days?.forEach((element) {
      List<AiPackItem>? list = data?.aiItem?.where(
        (e) => e.days == element
      ).toList();
      if(list != null) {
        itemList.add(list);
        priceSum.add(
          list.fold(0,
            (previous, e) => previous + (e.price ?? 0)
          )
        );
        choices.add(list.deepCopy);
      }
    });
    saleIndex = List.generate(days?.length ?? 0, (index) => null);
    for(var i =0;i< (days?.length ?? 0);i++){
      setSale(i);
    }
    update();
  }

  void setChoice(AiPackItem? item){
    if(!choices[index].any((element) => element.priceId == item?.priceId)){
      choices[index].add(item!);
      priceSum[index] = priceSum[index] + (item.price ?? 0);
    }else {
      choices[index].removeWhere((element) => element.priceId == item?.priceId);
      priceSum[index] = priceSum[index] - (item?.price ?? 0);
    }
    setSale(index);
    update();
  }

  void setChoiceAll(){
    if(choices[index].length == itemList[index].length){
      choices[index] = [];
      priceSum[index] = 0;
    }else{
      choices[index] = [];
      choices[index] = itemList[index].deepCopy;
      priceSum[index] = itemList[index].fold(0,
        (previous, e) => previous + (e.price ?? 0)
      );
    }
    setSale(index);
    update();
  }

  void setSale(int index){
    var hasFit = false;
    var count = choices[index].length;
    for(var i= 0;i<(saleRule?.length ?? 0);i++){
      var min = saleRule![i].minTotal;
      var max = saleRule![i].maxTotal ?? 0;
      if(min != null && count >= min && (count< max || max == 0)){
        saleIndex[index] = i;
        hasFit = true;
        break;
      }
    }
    if(!hasFit) saleIndex[index] = null;
    update();
  }

  double getDiscount(index) {
    if(saleIndex[index] != null){
      return saleRule?[saleIndex[index] ?? 0].discount ?? 1;
    }else{
      return 1;
    }
  }

  Future toPay() async{
    Utils.onEvent('center_model_buy');
    if(choices[index].isEmpty){
      ToastUtils.show("请选择模型工具");
      return;
    }
    double money = priceSum[index]*getDiscount(index);
    final PayResult? result = await Get.bottomSheet(
      isScrollControlled: true,
      PayBottomSheet(
        payInfo: PayInfo(
          price: money.toStringAsFixed(2),
          payScene: PayScene.aiPack,
          buyId: choices[index].map((e) => e.priceId).join('-')
        )
      )
    );
    if(result != null && result.toPay == PayStatus.goldPay){
      var s = await PayApi.aiPackOrder(choices[index].map((e) => e.priceId ?? 0).toList());
      if(s == true) {
        Utils.onEvent('pay_done');
        if(Get.previousRoute.contains(Routes.ai)){
          Get.back();
        }else{
          Get.toNamed(Routes.ai);
        }
      }else{
        Utils.onEvent('aizh_zfyd_qxzf');
      }
    }else if(result?.toPay == PayStatus.directPay){
      Utils.onEvent('aizh_zfyd_qrzf');
      if(Get.previousRoute.contains(Routes.ai)){
        Get.back();
      }else{
        Get.toNamed(Routes.ai);
      }
    }else{
      Utils.onEvent('aizh_zfyd_qxzf');
      ToastUtils.show("购买失败");
    }
    User.fetchUserInfo(fetchFocus: false);
  }
}